package com.zhiwei.codesecurity.common.utils;

import org.aspectj.util.FileUtil;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class JGitUtils {
    private static Logger logger = LoggerFactory.getLogger(JGitUtils.class);

    public static void cloneRepository(String remoteUrl, String account, String password, String branch, String localPath) {
        try {
            logger.info("====<<< cloneRepository执行开始|remoteUrl={}", remoteUrl);
            File localFile = new File(localPath);
            if (localFile.exists()) {
                logger.info("====<<< 删除本地已存在的同名文件夹|localFile={}", localFile);
                FileUtil.deleteContents(localFile);
            }
            UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =
                    new UsernamePasswordCredentialsProvider(account, password);
            CloneCommand cloneCommand = Git.cloneRepository().setURI(remoteUrl);
            Git git = cloneCommand.setURI(remoteUrl)
                    .setBranch(branch)
                    .setDirectory(localFile)
                    .setCredentialsProvider(usernamePasswordCredentialsProvider)
                    .call();
            logger.info("====<<< cloneRepository执行结束|gitRepository={}", git.getRepository());
        } catch (Exception e) {
            logger.error("====<<< cloneRepository执行异常, e.getMessage={}", e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        String localDir = UUIDUtil.getUUID();
        JGitUtils.cloneRepository("https://gitee.com/zhangxian_engineer/ZWCodeSecurityResponse.git",
                "zhangxian_engineer",
                "yang20120802",
                "master",
                "E:\\git\\" + localDir);
    }
}
